package com.wd.lobby.mgr;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.wd.command.BaseCommandObject;
import com.wd.entity.user.UserInfoEntity;
import com.wd.nio.SessionObject;
/**
 * @author long
 * @Create 2012-10-7 下午3:21:06
 * @QQ 108232706
 * @version 1.0
 * @description UserMgr
 */
final public class UserMgr {
	private static final Logger logger = LogManager.getLogger(UserMgr.class);
	// public DBMgr dbMgr;
	public static final Map<Integer, SessionObject> onlineUserMap =  new ConcurrentHashMap<Integer, SessionObject>();
	public static final ArrayList<SessionObject> onlineUserList = new ArrayList<SessionObject>();

	public static void clearAllUserList() {
		UserMgr.onlineUserMap.clear();
		UserMgr.onlineUserList.clear();	
	}
	public static void loginOff(SessionObject session) {
		UserInfoEntity user = session.getUser();
		if (user != null) {
			UserMgr.onlineUserMap.remove(user.getUserId());
			UserMgr.onlineUserList.remove(session);
		}
	}

	/**
	 * 游戏服注销中心服成功
	 * 
	 * @param serverid
	 * @param session
	 */
	public static void loginOff(int serverid, SessionObject session) {
		UserMgr.onlineUserMap.remove(serverid);
		UserMgr.onlineUserList.remove(session);
	}

	public static void loginOn(SessionObject session) {
		if (!session.isConnect())
			return;
		UserInfoEntity user = session.getUser();
		if (user != null) {
			UserMgr.onlineUserMap.put(user.getUserId(), session);
			UserMgr.onlineUserList.add(session);
		}
	}

	/**
	 * 游戏服连中心服成功
	 * 
	 * @param serverid
	 * @param session
	 */
	public static void loginOn(int serverid, SessionObject session) {
		if (!session.isConnect())
			return;
		UserMgr.onlineUserMap.put(serverid, session);
		UserMgr.onlineUserList.add(session);
	}

	// public boolean broadCastToAllOnlines(short cmdId, ByteBuffer bytes) {
	// long t1 = System.currentTimeMillis();
	// for (int i = 0; i < onlineUserList.size(); i++) {
	// SendData(onlineUserList.get(i), cmdId, bytes);
	// }
	// long t2 = System.currentTimeMillis();
	// Log.info(String.format("[UserMgr][%s] 发送大喇叭,广播用户:%s,耗时%sms!",
	// DateUtil.format(new Date()), onlineUserList.size(), (t2 - t1)));
	// return true;
	// }

	public static boolean broadCastToAllOnlines(BaseCommandObject dataPacket) {
		long t1 = System.currentTimeMillis();
		for (int i = 0; i < onlineUserList.size(); i++) {
			SendData(onlineUserList.get(i), dataPacket);
		}
//		long t2 = System.currentTimeMillis();
//		Log.debug(String.format("[UserMgr]广播用户:%s,耗时%sms!", onlineUserList.size(), (t2 - t1)));
		return true;
	}

	/**
	 * 向整个房间玩家广播
	 * 
	 * @param socketCmd
	 * @return
	 */
//	public static boolean broadCastToRoomUsers(BaseCommandObject socketCmd) {
//		UserInfoEntity user = socketCmd.getUser();
//		if (user != null) {
//			ArrayList<SessionObject> roomUsers = RoomMgr.getRoom(user.roomId).roomUsers();
//			if (roomUsers != null) {
//				for (int i = 0; i < roomUsers.size(); i++) {
//					SendData(roomUsers.get(i), socketCmd);
//				}
//			}
//		}
//		return false;
//
//	}

	/**
	 * 向整个房间玩家广播
	 * 
	 * @param socketCmd
	 * @return
	 */
//	public static boolean broadCastToRoomUsers(RoomConfigItem room, BaseCommandObject dataPacket) {
//		if (room != null) {
//			ArrayList<SessionObject> roomUsers = room.roomUsers();
//			if (roomUsers != null) {
//				for (int i = 0; i < roomUsers.size(); i++) {
//					SendData(roomUsers.get(i), dataPacket);
//				}
//			}
//		}
//		return false;
//
//	}

//	public static boolean broadCastToRoomUsers(int roomid, BaseCommandObject dataPacket) {
//		RoomConfigItem room = RoomMgr.getRoom(roomid);
//		if (room == null) {
//			return false;
//		}
//		ArrayList<SessionObject> roomUsers = room.roomUsers();
////		System.out.println("广播当前房间人:" + roomUsers.size());
//		if (roomUsers != null) {
//			for (int i = 0; i < roomUsers.size(); i++) {
//				SendData(roomUsers.get(i), dataPacket);
//			}
//		}
//		return false;
//	}

	/**
	 * 向整个房间其他玩家广播
	 * 
	 * @param socketCmd
	 * @return
	 */
//	public static boolean broadCastToRoomOtherUsers(BaseCommandObject socketCmd) {
//		UserInfoEntity user = socketCmd.getUser();
//		if (user != null) {
//			RoomMgr.getRoom(user.roomId).RoomDoorLock().lock();
//			try {
//				ArrayList<SessionObject> roomUsers = RoomMgr.getRoom(user.roomId).roomUsers();
//				if (roomUsers != null) {
//					for (int i = 0; i < roomUsers.size(); i++) {
//						if (roomUsers.get(i) == socketCmd.sessionObject)
//							continue;
//						SendData(roomUsers.get(i), socketCmd);
//					}
//				}
//			} finally {
//				RoomMgr.getRoom(user.roomId).RoomDoorLock().unlock();
//			}
//		}
//		return false;
//
//	}

	// public boolean SendData(SessionObject sessionObj, short cmdId, ByteBuffer
	// bytes) {
	// bytes.position(0);
	// Log.debug(String.format("[UserMgr]========>准备发命令:%s name:%s length:%s",
	// cmdId, CommandSet.getCmdName(cmdId), bytes.remaining()));
	// synchronized (sessionObj.getSendBuffer()) {
	// ByteBuffer sendBuffer = sessionObj.getSendBuffer();
	// if (sendBuffer.remaining() < bytes.remaining()) {
	// Log.error(String.format("[UserMgr]用户[%s]的发送缓冲已经不足,消息长度[%s]，请检查!",
	// sessionObj, bytes.remaining()));
	// return false;
	// }
	// sendBuffer.putInt(29099);
	// sendBuffer.putInt(bytes.remaining() + 22);// length
	// sendBuffer.putShort(cmdId);// cmd
	// sendBuffer.putInt(1);// temp1
	// sendBuffer.putInt(2);// temp2
	// sendBuffer.putInt(3);// temp3
	// sendBuffer.put(bytes);
	// sessionObj.getHasSendData().set(true);
	//
	// }
	// return true;
	// }

	public static boolean SendData(SessionObject sessionObj, BaseCommandObject dataPacket) {
		System.out.println("SendData包结:");
		if (dataPacket.getCmd() < 1) {
			logger.error("cmdid error");
			return false;
		}
		dataPacket.position(0);
		SocketChannel channel = sessionObj.getChannel();
		if (sessionObj.sessionKey == null) {
			return false;
		}
		synchronized (channel) {
			ByteBuffer sendBuffer = sessionObj.getSendBuffer();
			if (sendBuffer.remaining() < dataPacket.remaining() + 22) {
//				Log.error(String.format("[UserMgr]用户[%s]的发送缓冲已经不足,消息长度[%s]，请检查!", sessionObj, dataPacket.remaining()));
				return false;
			}
			sendBuffer.putInt(29099);
			sendBuffer.putInt(dataPacket.remaining() + 22);// length
			sendBuffer.putShort(dataPacket.getCmd());// cmd
			sendBuffer.putInt(1);// temp1
			sendBuffer.putInt(2);// temp2
			sendBuffer.putInt(3);// temp3
			sendBuffer.put(dataPacket.getBytes());
			sendBuffer.flip();
			while (sessionObj.sessionKey != null&&sendBuffer.remaining() > 0) {
				try {
					channel.write(sendBuffer);
				} catch (IOException e) {
					e.printStackTrace();
					logger.info(e);
				}
			}
			System.out.println("SendData包结成功");
			sendBuffer.compact();
		}
		return true;
	}

	public static boolean SendData(BaseCommandObject socketCmd) {
		return UserMgr.SendData(socketCmd.sessionObject, socketCmd);
	}


}
